<template>
  <el-dialog :model-value="dialogVisible" :title="dialogDatas.title" :destroy-on-close="true" @close="closeDialog">
    <div>
      <p class="mx1 mb10 font-bold text-base">基础信息</p>
      <el-form style="height:350px;overflow: auto;" ref="ruleFormRef" :model="ruleForm" :rules="rules"
        label-width="120px" class="demo-ruleForm" :disabled="dialogDatas?.type == 'check'">

        <el-form-item label="头像" prop="avatar">
          <el-upload list-type="picture-card" :auto-upload="true" :show-file-list="false" :before-upload="beforeUpload">
            <img class="preview-img" v-if="ruleForm.avatar" :src="ruleForm.avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus :size="18" />
              <span style="font-size: 12px;">添加头像</span>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="ruleForm.phone" placeholder="请输入手机号码" oninput="value=value.replace(/[^\d]/g,'')" clearable
            maxlength="11" />
        </el-form-item>
        <el-form-item label="员工姓名" prop="employeeName">
          <el-input v-model="ruleForm.employeeName" placeholder="请输入员工姓名" clearable maxlength="10" />
        </el-form-item>
        <el-form-item label="归属组织机构" prop="orgId">
          <el-select v-model="ruleForm.orgId" class="w-full" placeholder="请选择归属组织机构" @change="changeOrgId"
            v-if="showOrg">
            <el-option v-for="(item) in orgIdDatas" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否健康顾问" prop="isHealthDoctor">
          <el-select v-model="ruleForm.isHealthDoctor" class="w-full" :disabled="ruleForm.orgId === 99" placeholder="请选择是否健康顾问" @change="isjkgwchange">
            <el-option v-for="(item) in isHealthDoctorDatas" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="归属检测点" prop="checkPoints" v-if="showgsjcd">
          <el-select v-model="ruleForm.checkPoints" class="w-full" placeholder="请选择归属检测点">
            <el-option v-for="(item) in checkPointsOptionsDatas.array" :key="item.id" :label="item.name"
              :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="userStatus">
          <el-select v-model="ruleForm.userStatus" class="w-full" placeholder="请选择状态">
            <el-option v-for="(item) in userStatusDatas" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds" v-if="showjuese">
          <el-select v-model="ruleForm.roleIds" class="w-full" placeholder="请选择角色" multiple>
            <el-option v-for="(item) in roleDatas.array" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <p class="mx1 mb10 font-bold text-base">辅助信息</p>
        <el-form-item label="邮箱地址">
          <el-input v-model="ruleForm.email" placeholder="请输入邮箱地址" maxlength="30" />
        </el-form-item>
        <el-form-item label="当前职务">
          <el-input v-model="ruleForm.currentPosition" placeholder="请输入当前职务" maxlength="10" />
        </el-form-item>
        <el-form-item label="座机">
          <el-input v-model="ruleForm.telephone" placeholder="请输入座机" maxlength="10" />
        </el-form-item>
        <el-form-item label="员工性别">
          <!-- <el-radio-group v-model="ruleForm.gender" class="ml-2" placeholder="请选择员工性别">
            <el-radio :value="1" >男</el-radio>
            <el-radio :value="2" >女</el-radio>
          </el-radio-group> -->
          <el-radio-group v-model="ruleForm.gender" placeholder="请选择员工性别">
            <el-radio :label="radio.label" v-for="(radio, radioIndex) in xboptions" :key="radioIndex">{{ radio.value
              }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-input v-model="ruleForm.department" placeholder="请输入所属部门" maxlength="30" />
        </el-form-item>
        <el-form-item label="学历" v-if="showeducation">
          <el-select v-model="ruleForm.education" class="w-full" placeholder="请选择学历">
            <el-option v-for="(item) in educationOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="工号">
          <el-input v-model="ruleForm.jobNumber" placeholder="请输入工号" maxlength="10" />
        </el-form-item>
        <el-form-item label="籍贯">
          <el-input v-model="ruleForm.nativePlace" placeholder="请输入籍贯" maxlength="10" />
        </el-form-item>
        <el-form-item label="毕业院校">
          <el-input v-model="ruleForm.almaMater" placeholder="请输入毕业院校" maxlength="20" />
        </el-form-item>
        <el-form-item label="毕业时间">
          <el-date-picker v-model="ruleForm.graduationDate" type="date" placeholder="请选择毕业时间" format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"></el-date-picker>
        </el-form-item>
        <el-form-item label="所学专业">
          <el-input v-model="ruleForm.major" placeholder="请输入所学专业" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="ruleForm.notes" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer v-if="!(dialogDatas?.type == 'check')">
      <span class="dialog-footer" style="display: block;text-align: center;">
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="confirm(ruleFormRef)">确认</el-button>
      </span>
    </template>
    <template #footer v-if="(dialogDatas?.type == 'check')">
      <span class="dialog-footer" style="display: block;text-align: center;">
        <el-button @click="resetForm(ruleFormRef)">关闭</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 图片裁剪组件 -->
  <UploadAndCropperfrom :visible="isShowCorpper" :image="selectPic" @close="hideCorpper" :isCompress="true" />
</template>
<script lang="ts" setup>
import { ref, reactive, onBeforeMount, toRefs, nextTick } from 'vue';
import { enumListRequest, orgOptionsRequest, getCheckPointsOptionsRequest, roleOptionsRequest, uploadFileByPublicRequest } from '@/api/common';
import { getadminUserSave, adminUserEditRequest, getInfoRequest } from '@/api/system/adminUser/index';
import UploadAndCropperfrom from "@/components/uploadAndCropper/index.vue";

import type { FormInstance, FormRules } from 'element-plus';
const emit = defineEmits(['updateList', 'changeCheck', 'update:dialogVisible']);
const visible = ref(false);
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  dialogDatas: {
    type: Object,
    default: () => { }
  }
});
const { dialogVisible, dialogDatas } = toRefs(props);
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  id: null,
  phone: '',
  avatar: '',
  employeeName: '',
  isHealthDoctor: '',
  orgId: '',
  checkPoints: '',
  userStatus: '',
  roleIds: {},
  email: '',
  currentPosition: '',
  telephone: '',
  gender: '1',
  department: '',
  education: null,
  jobNumber: '',
  nativePlace: '',
  almaMater: '',
  graduationDate: '',
  major: '',
  notes: '',
})
// 校验
const rules = reactive<FormRules>({
  avatar: [{ required: true, message: '请上传头像', trigger: 'change' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'change' }],
  employeeName: [{ required: true, message: '请输入员工姓名', trigger: 'change' }],
  orgId: [{ required: true, message: '选择归属组织', trigger: 'change' }],
  checkPoints: [{ required: true, message: '选择归属检测点', trigger: 'change' }],
  isHealthDoctor: [{ required: true, message: '选择是否健康顾问', trigger: 'change' }],
  userStatus: [{ required: true, message: '选择状态', trigger: 'change' }],
  roleIds: [{ required: true, message: '选择角色', trigger: 'change' }],
})
let checkPointsOptionsDatas = reactive({ array: [] }); //归属检测点下拉数据
let roleDatas = reactive({ array: [] }); //角色
let showOrg = ref(true)
let showjuese = ref(false)
let showOrgs = ref(true)
//  组织机构变化-》获取归属枚举值
const changeOrgId = async () => {
  showOrg.value = false;
  ruleForm.checkPoints = '';
  ruleForm.roleIds = '';
  if(ruleForm.orgId === 99) {
    ruleForm.isHealthDoctor =  false
    isjkgwchange()
  } else {
    ruleForm.isHealthDoctor = ''
  }
  const data: any = await getCheckPointsOptionsRequest({ orgId: ruleForm.orgId });
  checkPointsOptionsDatas.array = data.data;
  const roledata: any = await roleOptionsRequest({ orgId: ruleForm.orgId });
  roleDatas.array = roledata.data
  showOrg.value = true
  showjuese.value = true
}
let showgsjcd = ref(false)
const isjkgwchange = async () => {
  if (ruleForm.isHealthDoctor) {
    showgsjcd.value = true
  } else {
    showgsjcd.value = false
  }

}

//提交
const confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if(saveFile.value) {
        const formData = new FormData();
        formData.append('files', saveFile.value)
        const imgRes = await uploadFileByPublicRequest(formData)
        ruleForm.avatar = imgRes.data.url[0]
      }
      let Url = dialogDatas.value.type == 'add' ? getadminUserSave : adminUserEditRequest;
      let res: any = await Url(ruleForm);
      if (res.code === 2000) {
        ElMessage.success('保存成功')
        emit("update:dialogVisible", false);
      } else {
        ElMessage.error(res.message)
      }
      formEl.resetFields()//重置
      emit('updateList')

    } else {
      console.log('保存失败', fields)
    }
  })
}
// 取消&重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  visible.value = false
  emit('updateList')
  emit("update:dialogVisible", false);
}
// 关闭
const closeDialog = () => {
  emit('updateList')
}
var userStatusDatas = reactive([{ id: 1, name: '在职启用' },
{ id: 2, name: '在职停用' },
{ id: 3, name: '离职' }]);
let isHealthDoctorDatas = reactive([{ id: true, name: '是' },
{ id: false, name: '否' }]);
let xboptions = reactive([
  { value: '男', label: 1 },
  { value: '女', label: 2 },
])
// 归属机构下拉
let orgIdDatas = reactive([])
// let showOrg = ref(true)
const getOrgOptionsDatas = async () => {
  showOrg.value = false
  const data: any = await orgOptionsRequest({ containBase: true });
  orgIdDatas = data.data;
  showOrg.value = true
};

// 学历下拉
let educationOptions = reactive([]);
const showeducation = ref(true)
const geteducationOptions = async () => {
  showeducation.value = false;
  const data: any = await enumListRequest({ enumName: 'EducationEnum' });
  educationOptions = data.data;
  console.log(educationOptions, 'educationOptions')
  showeducation.value = true;
};

// 获取详情
const getDetailsFun = async () => {
  const data: any = await getInfoRequest({ id: dialogDatas.value.datas.id });
  let res = data.data
  showOrgs.value = false
  showOrg.value = false

  showOrgs.value = true
  showjuese.value = true
  ruleForm.id = res.id
  ruleForm.phone = res.phone
  ruleForm.employeeName = res.employeeName
  ruleForm.isHealthDoctor = res.isHealthDoctor
  ruleForm.orgId = res.orgId
  ruleForm.checkPoints = res.checkPoints
  ruleForm.userStatus = res.userStatus
  ruleForm.roleIds = res.roleIds
  ruleForm.avatar = res.avatar
  console.log(ruleForm.roleIds, "ruleForm.roleIds")
  showOrg.value = true
  ruleForm.email = res.email
  ruleForm.currentPosition = res.currentPosition
  ruleForm.telephone = res.telephone
  ruleForm.gender = res.gender
  showgsjcd.value = res.isHealthDoctor
  ruleForm.department = res.department
  if (res.education == null) {
    ruleForm.education = null
  } else {
    ruleForm.education = res.education * 1
  }
  ruleForm.jobNumber = res.jobNumber
  ruleForm.nativePlace = res.nativePlace
  ruleForm.almaMater = res.almaMater
  ruleForm.graduationDate = res.graduationDate

  ruleForm.major = res.major
  ruleForm.notes = res.notes
  setTimeout(() => {
    ruleFormRef.value.clearValidate()
  }, 100);
}

let saveFile = ref()
let selectPic = ref("")
let isShowCorpper = ref(false)

/** 选择文件 */
function beforeUpload(file) {
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    selectPic.value = String(reader.result)
    isShowCorpper.value = true
  }
  return false
}

function hideCorpper(data) {
  isShowCorpper.value = false

  if (data) {
    const { result: { dataURL, blobURL }, file } = data
    ruleForm.avatar = dataURL;
    console.log(dataURL);

    saveFile.value = file
    ruleFormRef.value?.clearValidate()
  }
}
function saveForm() {
  // const files = new window.FormData(saveFile.value)
  const formData = new FormData();
  formData.append('files', saveFile.value)
  uploadFileByPublicRequest(formData).then(res => {
    console.log(res);

  })
}
onBeforeMount(async () => {
  getOrgOptionsDatas()//归属机构下拉
  geteducationOptions()// 学历下拉
  if (dialogDatas.value.datas?.orgId) {
    const checkPoints: any = await getCheckPointsOptionsRequest({ orgId: dialogDatas.value.datas.orgId }); //根据组织id查询检测点下拉数据
    checkPointsOptionsDatas.array = checkPoints.data;
    const roledata: any = await roleOptionsRequest({ orgId: dialogDatas.value.datas.orgId });//角色
    roleDatas.array = roledata.data
  }
  if (dialogDatas.value.type == 'add') {
    showjuese.value = false
  } else {
    getDetailsFun()
  }
})
</script>

<style lang="scss" scoped>
.el-dialog__footer {
  text-align: center;
}

.avatar-uploader-icon {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  font-style: normal;
}
</style>
